package com.ruoyi.learn.java.collection;

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        // 1. 默认保持插入顺序
        LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("apple", 1);
        linkedHashMap.put("banana", 2);
        linkedHashMap.put("cherry", 3);

        // 迭代时会按照插入顺序输出：apple -> banana -> cherry
        for (Map.Entry<String, Integer> entry : linkedHashMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }

        // 2. 按访问顺序（最后访问的元素放在末尾）
        LinkedHashMap<String, Integer> accessOrderMap = new LinkedHashMap<>(16, 0.75f, true);
        accessOrderMap.put("a", 1);
        accessOrderMap.put("b", 2);
        accessOrderMap.put("c", 3);

        accessOrderMap.get("a"); // 访问 "a"，会被移到末尾
        // 迭代顺序：b -> c -> a
        // 迭代时会按照插入顺序输出：apple -> banana -> cherry
        for (Map.Entry<String, Integer> entry : accessOrderMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}
